<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '开通会员红娘合伙人',
  },
}
</route>

<template>
  <view>
    <view class="w-750rpx m-a pt-32rpx"
      :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
    >
      <!-- 用户信息 -->
      <view class="flex-sb-center pl-32rpx pr-32rpx pt-16rpx pb-16rpx">
        <base-img-box :size="138" :round="138" :imgSrc="user.getUseVo.personAvatar.preUrl" :thumbnailPreUrl="user.getUseVo.personAvatar.thumbnailPreUrl" />
        <view class="w-516rpx">
          <view class="font-size-32rpx font-bold mt-8rpx" v-if="user.userInfo.matchmakerFlag">
            {{ user.matchmakerInfo.name || '未完善资料' }}
          </view>
          <view class="font-size-32rpx font-bold mt-8rpx" v-else>
            {{ user.getUseVo.userProfileInfoVo.nickname || user.userInfo.username || '未完善资料' }}
          </view>
          <view class="color-white bg-#986DF0 rounded-full font-size-24rpx inline-block h-42rpx mt-28rpx leading-40rpx pl-26rpx pr-26rpx"
            v-if="user.userInfo.membershipFlag"
          >
            到期时间：{{ user.userInfo.userMembershipInfoVo ? formatDate(new Date(user.userInfo.userMembershipInfoVo.endTime)) : '--' }}
          </view>
          <view class="color-white bg-#B4B4B4 rounded-full font-size-24rpx inline-block h-42rpx mt-28rpx leading-40rpx pl-26rpx pr-26rpx"
            v-else
          >暂未开通</view>
        </view>
      </view>

      <view class="w-center font-size-32rpx color-#2E1305 pt-82rpx">会员</view>

      <!-- 套餐列表 -->
      <view class="w-center pt-16rpx flex-sb-center flex-wrap">
        <package-item
          v-for="(item, index) in packageInfoList" 
          :key="index"
          :data="item"
          status="vip"
          :dotClass="themeConfig.theme === 'dark' ? '' : '!bg-#F7F8FA'"
          :selectPackageId="fromData.membershipId"
          @handleClick="handleClickPackage"
        />
      </view>
      
      <view class="w-center font-size-32rpx color-#2E1305 pt-40rpx">全民红娘</view>

      <!-- 套餐列表 -->
      <view class="w-center pt-16rpx flex-sb-center">
        <package-item
          v-for="(item, index) in getOfflineVipList" 
          :key="index"
          :data="item"
          status="vip"
          :itemWrapStyle="{ width: '200rpx !important' }"
          :dotClass="themeConfig.theme === 'dark' ? '' : '!bg-#F7F8FA'"
          :selectPackageId="fromData.membershipId"
          @handleClick="handleClickPackage"
        />
      </view>
      
      <view class="w-center font-size-32rpx color-#2E1305 pt-40rpx">合伙人</view>

      <!-- 套餐列表 -->
      <view class="w-center pt-16rpx flex-sb-center flex-wrap">
        <package-item
          v-for="(item, index) in partnerList" 
          :key="index"
          :data="item"
          status="vip"
          :itemWrapStyle="{ width: '200rpx !important' }"
          :dotClass="themeConfig.theme === 'dark' ? '' : '!bg-#F7F8FA'"
          :selectPackageId="fromData.membershipId"
          @handleClick="handleClickPackage"
        />
      </view>

      <view class="w-750rpx m-a bg-white !mt-28rpx"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <view class="w-center color-#2E1305 font-size-32rpx leading-38rpx !pt-36rpx"
          :class="[{ '!color-white': themeConfig.theme === 'dark' }]"
        >权益</view>

        <view class="w-center pt-22rpx pb-62rpx flex-sb-center flex-wrap">
          <view class="pt-38rpx w-208rpx text-center" 
            v-for="(item, index) in getVipPowerList" 
            :key="index"
          >
            <wd-img width="64rpx" height="64rpx" round :src="icons[`${item.icon}`]" />

            <view class="color-#2E1305 font-size-24rpx leading-33rpx mt-16rpx min-h-66rpx"
              style="white-space: pre-line;"
              :class="[{ '!color-white': themeConfig.theme === 'dark', '!min-h-98rpx': item.len === 3 }]"
            >
              {{ item.name }}
            </view>
          </view>
          <view class="pt-38rpx text-center w-208rpx h-1rpx"
            v-if="getVipPowerList.length % 3 !== 0"
          ></view>
        </view>
      </view>

      <view class="w-full" :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }">
        <view class="h-126rpx"></view>
      </view>
    </view>
    
    <view class="position-b-center !fixed w-750rpx m-a pt-24rpx bg-white box-sd"
      :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }"
      :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
    >
      <!-- 立即开通 -->
      <view class="btn-full w-center pb-24rpx">
        <wd-button 
          class="btn-w-full btn-h-78"
          :loading="loading"
          @click="submit"
        >立即开通</wd-button>
      </view>
    </view>
  </view>
</template>
  
<script lang="ts" setup>
import PackageItem from "@/components/list-item/package-item.vue";
import baseImgBox from "@/components/base/base-img-box.vue";
import { enumParams } from "@/enum";
import { GetMemberList, GetPartnerCategoryConfigList, OfflineServiceProviderQueryByUserId, UserMembershipInfoMembership } from "@/service/db_feature";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { icons } from "@/utils/icons";
import { useToast } from "wot-design-uni";
import { formatDate, isIOS } from "@/utils";
import { deepClone } from "wot-design-uni/components/common/util";
import { GetDefaultAmountConfigQueryCode } from "@/service/db_index";
import { Main } from "@/service/types";

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 主题颜色
const { themeConfig } = useThemeStore();
const user = useUserStore();
const common = useCommonStore();
const toast = useToast();

// 线下服务商详情
const providerDetail = ref<any>({});
const toMatchmaker = () => {
  uni.navigateTo({ url: '/feature/addMatchmaker' })  
}

const fromData = reactive({
  userId: user.userInfo.id,
  membershipId: ''
})

// 办理会员
const loading = ref(false);
const submit = async () => {
  const userProfileInfoVo: any = user.userInfo.userProfileInfoVo || {};
  let tip = '';
  if (!userProfileInfoVo.nickname) {
    tip = '请先完善个人资料';
  }
  if (!user.userInfo.verificationFlag) {
    tip = '请先完成实名认证';
  }
  if (tip) {
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/info' });
    }, 1000)
    return toast.show(tip);
  }

  // 全民红娘
  if (selectedIndex.value === 4) {
    toMatchmaker();
    return
  }
  // 初级/中级/高级
  if (selectedIndex.value > 4) {
    const partner = partnerList.value.find(item => item.selectedIndex === selectedIndex.value);
    // 当前等级
    const currentPartnerType = providerDetail.value.partnerType;
    const currentCategoryCode = currentPartnerType ? enumParams.categoryCodeOption[currentPartnerType] : 0;
    // 选择的等级
    const selectedCategoryCode = enumParams.categoryCodeOption[partner.categoryCode] || 0;
    if (currentCategoryCode >= selectedCategoryCode) {
      toast.show('开通的等级不能比当前等级低！');
      return;
    }
    uni.navigateTo({ url: '/feature/apply?type=0&categoryCode=' + partner.categoryCode });
    return
  }
  
  if (!fromData.membershipId) return toast.show('请选择套餐!');
  loading.value = true;
  try {
    uni.showLoading({
      title: '正在调起支付'
    });
    const res = await UserMembershipInfoMembership(fromData);
    loading.value = false;
    if (res.code != 200) {
      uni.hideLoading();
      return toast.show(res.message);
    }
    payment(res.data);
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
}

// 调起微信支付
const payment = ({
  nonceStr, packageValue, paySign, signType, timeStamp
}) => {
  if (isIOS() && common.chargeConfig.typeName === 'false') {
    uni.showToast({
      title: '由于相关规范，iOS功能暂不可用',
      icon: 'none'
    })
    return 
  }
  wx.requestPayment({
    timeStamp,
    nonceStr,
    package: packageValue,
    signType,
    paySign,
    success: (res) => {
      uni.hideLoading();
      user.loginSubmit = true;
      toast.show('开通成功！');
      user.getUserInfo();
    },
    fail: (err) => {
      uni.hideLoading();
      console.log('fail:' + JSON.stringify(err));
    }
  })
}

const selectedIndex = ref(0);
const getVipPowerList = computed(() => {
  const list = enumParams.vipPowerList[selectedIndex.value] || [];
  return list.filter((item) => item.hasBenefit);
})

const getOfflineVipList = computed(() => {
  const list = deepClone(enumParams.offlineVipList);
  list.forEach((item, index) => {
    item.price = amount.value;
  })
  return list;
})

const amount = ref(0);
// 全民红娘金额
const getDefaultAmountConfigQueryCode = async () => {
  try {
    const res = await GetDefaultAmountConfigQueryCode({
      code: 'matchmaker_save'
    })
    const data = res.data || {} as Main.DefaultAmountConfigQueryCode;
    amount.value = data.amount || 0;
  } catch (error) {
    console.log(error);
  }
}

// 获取会员配置表列表
const packageInfoList = ref(enumParams.vipList);
// 合伙人列表
const partnerList = ref([]);
const getMemberList = async () => {
  const res = await GetMemberList({});
  
  const list = res.data || [];
  list.sort((a, b) => a.currentPrice - b.currentPrice);
  // selectedIndex 0/1/2/3
  packageInfoList.value = list.filter((item, index) => index <= 3).map((item, index) => {
    return {
      name: item.membershipName,
      price: item.currentPrice,
      give: item.originalPrice,
      selectedIndex: index,
      ...item
    }
  })
  
  fromData.membershipId = list[0].id;
  selectedIndex.value = 0;
}

// 获取合伙人类别配置列表
const getPartnerCategoryConfigList = async() => {
  try {
    const res = await GetPartnerCategoryConfigList({});
    const list = res.data || [];
    
    // 全民红娘为4
    // selectedIndex 5/6/7
    partnerList.value = list.map((item, index) => {
      return {
        name: item.categoryName,
        price: item.price,
        give: item.originalPrice,
        selectedIndex: 5 + index,
        ...item
      }
    })
    // 获取线下服务商详情
    getOfflineServiceProvider();
  } catch (error) {
    console.log(error)
  }
}

// 根据id获取线下服务商表详情
const getOfflineServiceProvider = async (type = 'partner') => {
  const res = await OfflineServiceProviderQueryByUserId({
    userId: user.userInfo.id,
    type,
  });
  const data = res.data || {};
  providerDetail.value = data;
} 

const handleClickPackage = (data) => {
  fromData.membershipId = data.id;
  selectedIndex.value = data.selectedIndex;
}

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '开通会员红娘合伙人';
  })
  getMemberList();
  getPartnerCategoryConfigList();
  getDefaultAmountConfigQueryCode();
})
</script>

<style lang="scss" scoped>
</style>
    